package com.dragon.english_practice_back.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Map;

@Slf4j
@Component
public class JWTUtil {
    private static final String SIGNATURE = "token!171819";
    /**
     * 生成token
     * @param map //传入payload
     * @return 返回token
     */
    public static String createToken(Map<String,String> map){
        JWTCreator.Builder builder = JWT.create();
        //插入数据
        map.forEach(builder::withClaim);
        //获取当前时间
        Calendar instance = Calendar.getInstance();
        //制作过期时间
        instance.add(Calendar.YEAR,100);
        //设置token超时时间
        builder.withExpiresAt(instance.getTime());
        return builder.sign(Algorithm.HMAC256(SIGNATURE));
    }

    //解析token
    public static DecodedJWT getToken(String token){
        return JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    }
    /*
    查询内容username: DecodedJWT.getClaim("username").asString()
    查询过期时间: DecodedJWT.getExpiresAt()
     */

    //判断token是否过期
    public static boolean isExceedTime(String token){
        return !stillTimeRemaining(token, 0);
        
    }

    public static boolean stillTimeRemaining(String token, long time){
        if(time < 0){
            log.error("need time > 0, time:{}", time);
        }
        try{
            DecodedJWT decodedJWT = getToken(token);
            long tokenTime = decodedJWT.getExpiresAt().getTime();
            long sysTime = System.currentTimeMillis();

            return tokenTime > (sysTime + time);

        }
        catch (TokenExpiredException e){
            return false;
        }

    }
}
